from typing import List, Optional
from sqlalchemy.orm import Session
from app.db.crud import create_source
from app.db.database import SessionLocal
import logging
from app.db.models import TSource

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()  # 添加 StreamHandler 确保日志输出到标准输出
    ]
)
logger = logging.getLogger(__name__)

class SourceController:
    def create_source(self, name: str, url: str, username: str, is_user_define: bool, create_user: str) -> bool:
        try:
            with SessionLocal() as db:
                # 判断是否存在该数据源
                source = db.query(TSource).filter(TSource.name == name).first()
                if source:
                    logger.info(f"Source {name} already exists")
                    return True
                logger.info(f"Creating source: {name}")
                source = create_source(
                    db=db,
                    name=name,
                    url=url,
                    username=username,
                    is_user_define=is_user_define,
                    create_by=create_user
                )
                return True if source else False
        except Exception as e:
            logger.error(f"Error creating source {name}: {str(e)}")
            return False

    def init_sources(self):
        """初始化所有数据源"""
        logger.info("Starting source initialization...")
        sources = [
            # 百度热搜
            ('baidu', 'https://top.baidu.com/board?tab=realtime', 'ting', False, 'ting'),
            
            # B站热搜
            ('bilibili', 'https://s.search.bilibili.com/main/hotword', 'ting', False, 'ting'),
            
            # Hacker News
            ('hackernews', 'https://news.ycombinator.com', 'ting', False, 'ting'),
            
            # 百度贴吧热门
            ('tieba', 'https://tieba.baidu.com/hottopic/browse/topicList', 'ting', False, 'ting'),
            
            # 参考消息
            ('cankaoxiaoxi', 'https://china.cankaoxiaoxi.com', 'ting', False, 'ting'),
            
            # 雪球热门股票
            ('xueqiu', 'https://stock.xueqiu.com/v5/stock/hot_stock/list.json', 'ting', False, 'ting'),
            
            # 抖音热搜
            ('douyin', 'https://www.douyin.com/aweme/v1/web/hot/search/list/', 'ting', False, 'ting'),
            
            # FastBull财经
            ('fastbull-express', 'https://www.fastbull.com/cn/express-news', 'ting', False, 'ting'),
            ('fastbull-news', 'https://www.fastbull.com/cn/news', 'ting', False, 'ting'),
            
            # 格隆汇
            ('gelonghui', 'https://www.gelonghui.com/news/', 'ting', False, 'ting'),
            
            # 澎湃新闻
            ('thepaper', 'https://cache.thepaper.cn/contentapi/wwwIndex/rightSidebar', 'ting', False, 'ting'),
            
            # V2EX
            ('v2ex-create', 'https://www.v2ex.com/feed/create.json', 'ting', False, 'ting'),
            ('v2ex-ideas', 'https://www.v2ex.com/feed/ideas.json', 'ting', False, 'ting'),
            ('v2ex-programmer', 'https://www.v2ex.com/feed/programmer.json', 'ting', False, 'ting'),
            ('v2ex-share', 'https://www.v2ex.com/feed/share.json', 'ting', False, 'ting'),

            # 微博热搜
            ('weibo', 'https://s.weibo.com/top/summary', 'ting', False, 'ting'),

            # 头条热搜
            ('toutiao', 'https://www.toutiao.com/api/pc/feed/hot_list/v1/tab_hot_list/news_hot_list/1?tab_id=news_hot_list&refresh_count=1&count=20&_signature=a1234567890', 'ting', False, 'ting'),

            # 36氪热榜
            ('kr36', 'https://www.36kr.com/hot-list/0', 'ting', False, 'ting'),
        ]
        
        success_count = 0
        for name, url, username, is_user_define, create_user in sources:
            if self.create_source(name, url, username, is_user_define, create_user):
                success_count += 1
                logger.info(f"Successfully created source: {name}")
            else:
                logger.error(f"Failed to create source: {name}")
        
        logger.info(f"Source initialization completed. Successfully created {success_count} out of {len(sources)} sources.")

# 初始化数据源
if __name__ == "__main__":
    try:
        logger.debug("Debug message")  # 添加不同级别的日志
        logger.info("Testing database connection...")
        logger.warning("Warning message")
        logger.error("Error message")
        with SessionLocal() as db:
            logger.info("Database connection successful!")
        
        controller = SourceController()
        controller.init_sources()
    except Exception as e:
        logger.error(f"Failed to initialize sources: {str(e)}")